import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# 读取数据集
def load_dataset(data_dir):
    X, y = [], []
    for label in os.listdir(data_dir):
        label_dir = os.path.join(data_dir, label)
        for img_file in os.listdir(label_dir):
            img_path = os.path.join(label_dir, img_file)
            img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)  # 以灰度模式读取图像
            img = cv2.resize(img, (100, 100))  # 将图像大小调整为100x100
            X.append(img.flatten())  # 将图像转换为一维数组并添加到特征集中
            y.append(label)
    return np.array(X), np.array(y)

# 加载数据集
data_dir = r'C:\Users\Harris\Documents\GitWarehouse\Dataset\d\CatDog'

X, y = load_dataset(data_dir)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y) # 使用stratify=y确保按类别均匀划分

# 使用原始像素作为特征进行分类
classifier = KNeighborsClassifier(n_neighbors=5)  # KNN分类器
classifier.fit(X_train, y_train)  # 在原始像素上训练分类器
y_pred = classifier.predict(X_test)  # 在测试集上进行预测

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy (without Dictionary Learning):", accuracy)
